import {useLoaderData, useNavigate} from "react-router-dom";
import {useLoginToken} from "../hooks/LoginHooks.tsx";
import {doGetQuestionInfo, doSaveOrUpdateQuestion, doUpdateQuestionContent, doUploadImg} from "../api/apis.ts";
import {Question} from "../types/commonTypes.ts";
import '../style/edit.scss'
import {Button, Divider, message, Tabs, Tag} from "antd";
import TextArea from "antd/es/input/TextArea";
import {useContext, useState} from "react";
import {TagOutlined} from '@ant-design/icons';
import {MdEditor} from 'md-editor-rt';
import 'md-editor-rt/lib/style.css';
import {DataContext} from "../provider/DataProvider.tsx";
import CheckableTag from "antd/es/tag/CheckableTag";

export async function loader({params}: any): Promise<Question> {
  useLoginToken();
  const qId = params.questionId;
  if (qId) {
    const {code, data, msg} = await doGetQuestionInfo(qId)
    if (code === 200) {
      return data;
    }
    // 错误处理
    throw new Error(msg);
  }
  return {
    title: '',
    description: '',
    tag: '',
  };
}

export default function EditQuestion() {
  const [question, setQuestion] = useState<Question>(useLoaderData() as Question)
  const shareData = useContext(DataContext);
  let initTags: string[] = [];
  if (question.tag?.length) {
    initTags = question.tag?.split(',');
  }
  const [selectedTags, setSelectedTags] = useState<string[]>(initTags);
  const [titleInputState, setTitleInputState] = useState({
    bordered: false,
    status: ''
  })
  const navigate = useNavigate();
  const handleChange = (tag: string, checked: boolean) => {
    if (checked && selectedTags.length >= 5) {
      message.warning('最多选择5个标签');
      return;
    }
    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter((t) => t !== tag);
    setSelectedTags(nextSelectedTags);
  };
  const initTagList = question.tag?.split(',');
  let initIndex = 0;
  if (initTagList) {
    for (const cat of shareData?.allTags || []) {
      if (cat.tags?.find((t) => initTagList.includes(t))) {
        initIndex = shareData?.allTags?.indexOf(cat) || 0;
        break;
      }
    }
  }
  const onSubmitQuestion = async () => {
    if (!question.title) {
      setTitleInputState({
        bordered: true,
        status: 'error'
      });
      message.error(`请输入问题标题`);
      return;
    }
    if (!question.description) {
      message.error(`请输入问题内容`);
      return;
    }
    question.tag = selectedTags.join(',') || '';
    const {code, data, msg} = await doSaveOrUpdateQuestion(question);
    if (code === 200) {
      message.success(`问题${question.id ? '修改' : '保存'}成功!`);
      navigate(`/question/index/${data}`);
    } else {
      message.error(msg);
    }
  }
  return (
    <div className='edit-container'>
      <div className='top-tip'>
        {
          question?.id ?
            '编辑问题' : '新建问题'
        }
      </div>
      <Divider/>
      <div className='edit-title'>
        <TextArea placeholder="请输入文章标题" value={question?.title}
                  className='edit-title-input'
                  autoSize
                  status={titleInputState.status as any}
                  bordered={titleInputState.bordered}
                  onChange={(e) => {
                    if (e.target.value) {
                      setTitleInputState({
                        bordered: false,
                        status: 'success'
                      })
                    }
                    setQuestion({...question, title: e.target.value})
                  }}/>
      </div>
      <Divider/>
      <MdEditor modelValue={question?.description || ''}
                onUploadImg={async (files, callBack) => {
                  const tasks = files.map((file) => {
                    return doUploadImg(file);
                  });
                  Promise.all(tasks).then(res => {
                    res.forEach(({code, data}) => {
                      if (code === 200) {
                        callBack([import.meta.env.VITE_API_URL + data])
                      }
                    })
                  });
                }}
                toolbarsExclude={question.id ? [] : ['save']}
                onSave={async (doc) => {
                  if (doc.length > 0) {
                    const {code, msg} = await doUpdateQuestionContent({
                      id: question.id,
                      description: doc,
                    });
                    if (code === 200) {
                      message.success('保存成功');
                    }else {
                      message.error(msg);
                    }
                  }else {
                    message.warning('内容不能为空');
                  }
                }}
                onChange={(doc) => {
                  setQuestion({...question, description: doc})
                }}/>
      <Divider/>
      {
        selectedTags?.length ?
          <div className='tag-input-container unselectable'>
            {selectedTags.map(tag =>
              <Tag
                key={tag}
                className='selected-tag'
                closable
                onClose={(e) => {
                  e.preventDefault();
                  setSelectedTags(selectedTags.filter(t => t !== tag))
                }}
              >
                <TagOutlined style={{marginRight: '3px'}}/>
                {tag}
              </Tag>
            )}
          </div>
          : ''
      }

      <Tabs
        className='tabs-select-container unselectable'
        defaultActiveKey={initIndex + ''}
        items={shareData?.allTags?.map((item) => {
          return {
            key: item.categoryId,
            label: item.categoryName,
            children: <>
              {
                item.tags?.map((tag) => (
                  <CheckableTag
                    className={'tag-select-item ' + (selectedTags.includes(tag) ? '' : 'unselected-tag')}
                    key={tag}
                    checked={selectedTags.includes(tag)}
                    onChange={(checked) => handleChange(tag, checked)}
                  >
                    <TagOutlined style={{marginRight: '3px'}}/>
                    {tag}
                  </CheckableTag>
                ))
              }
            </>,
          } as any;
        })}
      />
      <div className='submit-button'>
        <Button type="primary" onClick={() => onSubmitQuestion()}>
          提交
        </Button>
      </div>

    </div>
  );
}